package tgc.edu.yzy.web.controller;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.yzy.custom.ZtreeUtils;
import tgc.edu.yzy.entity.Dept;
import tgc.edu.yzy.service.DeptService;
import tgc.edu.yzy.web.form.DeptForm;

@Controller
public class DeptController {
	@Autowired
	private DeptService service;
	@RequestMapping(value="index")
	public String index() {
		return "index";
	}
	@RequestMapping(value="list")
	@ResponseBody
	public Object list(Integer id){
		List<Dept> list;
		if(id==null) {
			list=service.findByParentIsNull();
		}else {
			list=service.findByParentId(id);
		}
		//PId 转换问题 在get方法里 命名规则克制从getPId 改成getpId
		return ZtreeUtils.buildZtreeResult(list);
	}
	
	@RequestMapping(value="edit")
	public String edit(Integer id,ModelMap map) {
		Dept model = service.findById(id);
		map.put("model", model);
		return "edit";
	}
	@RequestMapping(value="save")
	public String save(DeptForm form) {
		Dept dept=new Dept();
		//将form的参数 传递到dept中  不传递parent
		BeanUtils.copyProperties(form, dept,"parent");
		//查找出dept传递过来的ID对应的数据
		Dept parent=service.findById(form.getpId());
		//将parent的集合的ID参数存到dept中  覆盖
		dept.setParent(parent);
		service.save(dept);
		return "redirect:index";
	}
	@RequestMapping(value="delete")
	@ResponseBody
	public Object delete(Integer id) {
		service.deleteById(id);
		return "OK";
	}
	@RequestMapping(value="rename")
	@ResponseBody
	public Object rename(Integer id,String name,Integer pId) {
		service.rename(id,name,pId);
		return "OK";
	}
	@RequestMapping(value="add")
	@ResponseBody
	public Object add(Integer pId) {
		Dept model=service.add(pId);
		return model;
	}
	@RequestMapping(value="/move")
	@ResponseBody
	public Object move(Integer id,Integer pId) {
		service.move(id,pId);
		return "ok";
	}
}
